package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.ValidateCodeUtils;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送手机短信验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //1.获取手机号
        String phone = user.getPhone();
        //2.发送验证码
        if (StringUtils.isNotEmpty(phone)){
            //随机生成一个4位的验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //调用阿里云短信服务 发送短信
//            SMSUtils.sendMessage("品优购","SMS_142946316",phone, code);
            log.info("您当前登录的验证码是：" + code);
            //发送成功 保存验证码到session中
            session.setAttribute(phone, code);
            return R.success("手机验证码发送成功");
        }
        return R.error("短信发送失败");
    }

    /**
     * 用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        //1.获取手机号
        String phone = map.get("phone").toString();
        //2.获取手机号验证码
        String code = map.get("code").toString();
        //3.从session中获取保存的验证码
        String codeSession = session.getAttribute(phone).toString();
        //4.进行验证码比较 不一致 返回登录失败
        if (codeSession != null && codeSession.equals(code)){
            //5.如果一致 登录成功
            //6.查询当前用户是否存在
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(lambdaQueryWrapper);
            //7.不存在 手动注册
            if (user == null){
                //手机登录的是新用户 需要注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //8.存储当前登录的用户id
            session.setAttribute("user", user.getId());
            //9.返回登录结果
            return R.success(user);
        }

        return R.error("验证码不正确");
    }
}
